package dao

import (
	"album/model"
	"context"
	"listenboos-common/db"
	"listenboos-common/db/gorms"
	"listenboos-common/tools"
	"time"
)

type AlbumStatDao struct {
	conn *gorms.GormConn
}

func NewAlbumStatDao(db *db.ListenDB) *AlbumStatDao {
	return &AlbumStatDao{
		conn: gorms.New(db.Conn),
	}
}
func (u *AlbumStatDao) FindByAlbumId(ctx context.Context, id int64) (playStatNum, subscribeStatNum, buyStatNum, commentStatNum string, err error) {
	session := u.conn.Session(ctx)
	err = session.Model(&model.AlbumStat{}).Where("album_id = ? and stat_type = 0401", id).Select("stat_num").Scan(&playStatNum).Error
	err = session.Model(&model.AlbumStat{}).Where("album_id = ? and stat_type = 0402", id).Select("stat_num").Scan(&subscribeStatNum).Error
	err = session.Model(&model.AlbumStat{}).Where("album_id = ? and stat_type = 0403", id).Select("stat_num").Scan(&buyStatNum).Error
	err = session.Model(&model.AlbumStat{}).Where("album_id = ? and stat_type = 0404", id).Select("stat_num").Scan(&commentStatNum).Error
	if err != nil {
		return "", "", "", "", err
	}
	return playStatNum, subscribeStatNum, buyStatNum, commentStatNum, nil
}
func (u *AlbumStatDao) Save(ctx context.Context, conn db.DBConn, id int64) error {
	u.conn = conn.(*gorms.GormConn)
	tx := u.conn.Tx(ctx)
	now := tools.ToTimeString(time.Now().UnixMilli())
	one := "0401"
	two := "0402"
	three := "0403"
	four := "0404"
	for i := 0; i < 4; i++ {
		stats := model.AlbumStat{}
		stats.AlbumId = id
		stats.CreateTime = now
		stats.UpdateTime = now
		if i == 0 {
			stats.StatType = one
			err := tx.Save(&stats).Error
			if err != nil {
				return err
			}
		}
		if i == 1 {
			stats.StatType = two
			err := tx.Save(&stats).Error
			if err != nil {
				return err
			}
		}

		if i == 2 {
			stats.StatType = three
			err := tx.Create(&stats).Error
			if err != nil {
				return err
			}
		}
		if i == 3 {
			stats.StatType = four
			err := tx.Save(&stats).Error
			if err != nil {
				return err
			}
		}

	}
	return nil
}
